const fs = require("fs");

// 1. 一次性写入内容
fs.writeFile(
  "./stream-file/writeFile.txt",
  "hello writeFile",
  {
    encoding: "utf-8", // 写入编码
    flag: "a+", // 写入模式
  },
  (err) => {
    console.log(err);
  }
);

// 2. 创建可写流
const writeStream = fs.createWriteStream("./stream-file/writeFile.txt", {
  flags: "a", // 写入模式
});

writeStream.on("open", (fd) => {
  console.log("文件被打开了", fd);
});

writeStream.write("writeStream");
writeStream.write("hello writeStream");
writeStream.write("hello writeStream success", (err) => {
  console.log("写入完成", err);
});

writeStream.on("finish", () => {
  console.log("写入完成");
});

writeStream.on("close", () => {
  console.log("文件被关闭了");
});

// 3.写入完成时, 需要手动去掉用close方法
// writeStream.close()

// 4.end方法:
// 操作一: 将最后的内容写入到文件中, 并且关闭文件
// 操作二: 关闭文件
writeStream.end("writeStream end");
